/**
 * 2018年12月15日下午2:47:17
 * @author 谢进财
 */
package com.baihang.project.ds.HandlerInterceptor;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;

import com.baihang.framework.kit.database.RedisKit;

import redis.clients.jedis.Jedis;

/**
 *  项目启动状态下的拦截器
 *
 */
public class StartInterceptor implements HandlerInterceptor {

    private final static Logger logger = LoggerFactory.getLogger(StartInterceptor.class);
    private Jedis jedis = RedisKit.getJedis();
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		logger.info("拦截前");
		String state = jedis.hmget("systemConfig","State").get(0);
		if("4".equals(state)) {//活动开启状态	
			if(isAjax(request)){
				response.setStatus(402);//直接返回401状态码
			}else {
				request.getRequestDispatcher("/finish").forward(request, response);				
			}
			return false;
		}
        return true;
		//return HandlerInterceptor.super.preHandle(request, response, handler);
	}
	
	private boolean isAjax(ServletRequest request){
        String header = ((HttpServletRequest) request).getHeader("X-Requested-With");
        if("XMLHttpRequest".equalsIgnoreCase(header)){
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }
}
